package com.android.bonn.fast.net.config;

import com.android.bonn.fast.net.utils.SSLUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;

/**
 * Created by huangyunlin on 2019-03-24.
 * fix
 */
public final class OkHttpConfig implements IOkHttpConfig {

    private static List<Interceptor> interceptors;
    private static List<Interceptor> networkInterceptors;

    public OkHttpConfig() {
        interceptors = new ArrayList<>();
        networkInterceptors = new ArrayList<>();
    }

    public void addInterceptor(Interceptor interceptor) {
        interceptors.add(interceptor);
    }

    public void addNetworkInterceptors(Interceptor interceptor) {
        networkInterceptors.add(interceptor);
    }

    public OkHttpClient build(boolean debug) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.retryOnConnectionFailure(true);
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);

        ConnectionPool pool = new ConnectionPool(10, 20, TimeUnit.MINUTES);
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequestsPerHost(10);
        dispatcher.setMaxRequests(50 * 5);

        builder.connectionPool(pool);
        builder.dispatcher(dispatcher);


        SSLUtil.SSLParams sslParams = getSSLConfig();
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);


        if (interceptors != null) {
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
        }

        if (networkInterceptors != null && networkInterceptors.size() > 0) {
            for (Interceptor interceptor : networkInterceptors) {
                builder.addNetworkInterceptor(interceptor);
            }
        }

        return builder.build();
    }

    public SSLUtil.SSLParams getSSLConfig() {
        return SSLUtil.getSslSocketFactory();
    }

    public void relase() {
        interceptors.clear();
    }

}
